<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共166条记录</span>
        <template #after>
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportData">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <!-- <el-table-column label="头像" align="center" width="130">
            <template slot-scope="{ row }">
              <img
                v-imagerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="手机号" sortable="" prop="mobile" /> -->
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <!-- <template slot-scope="obj"></template> -->
            <!-- 将时间进行格式化 -->
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <!-- slot-scope="{ row }" -->
            <template v-slot="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small">角色</el-button>
              <el-button type="text" size="small" @click="deleteEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 放置新增组件 -->
    <add-employee :show-dialog.sync="showDialog" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import { formatDate } from '@/filters'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee'
export default {
  name: 'Employees',
  components: {
    AddEmployee
  },
  data() {
    return {
      loading: false, //
      list: [], // 员工数据
      page: {
        page: 1, // 当前页码
        size: 10, // 每次加载数据
        total: 0 // 分页总数
      },
      showDialog: false // 新增弹窗开关
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    changePage(newPage) {
      this.page.page = newPage // 监听到切换页数,赋值给当前页面进行切换
      this.getEmployeeList() // 切换过后调取接口获取员工数据
    },
    // 调取接口获取数据
    async getEmployeeList() {
      this.loading = true // 打开加载动画
      const { total, rows } = await getEmployeeList(this.page) // 解构数据
      this.page.total = total
      this.list = rows
      this.loading = false // 关闭加载动画
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      // 要去枚举里面查找1所对应的值
      // row是行数据,column是列属性,cellValue是行单元格的值
      const obj = EmployeeEnum.hireType.find(item => item.id === +cellValue) // 隐式转换,后台返回的cellvalue可能会是字符串
      return obj ? obj.value : '未知'
    },
    // 调取接口删除员工
    async deleteEmployee(id) {
      try {
        // 提示用户是否确认
        await this.$confirm('您确定删除该员工吗')
        // 确认过后调取删除接口
        await delEmployee(id)
        // 删除之后重新获取最新数据
        this.getEmployeeList()
        // 给用户响应
        this.$message.success('删除员工成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 导出excel
    exportData() {
      // 表头对应关系
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 懒加载
      import('@/vendor/Export2Excel').then(async excel => {
        // page: this.page.total 的目的是要一次性把全部的员工列表查询出来
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        // [["张三", "13811111111"，"2018","1", "2018", "10002"],["李思", "13911111111"，"2018","1", "2018", "10002"],...]
        const data = this.formatJson(headers, rows) // 将表头数据和数据对应
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工信息表',
          multiHeader, // 复杂表头
          merges // 合并选项
        })
      })
    },
    // 该方法负责将数组转化成二维数组 [{},{}...] => [[],[],...]
    formatJson(headers, rows) {
      // 首先遍历数组
      //  [{ username: '张三', mobile: '13811111111', ...},{},{}]  => [[’张三', '13811111111',...],[],[]]
      return rows.map(item => {
        // Object.keys(headers) => ['姓名','手机号',...]
        return Object.keys(headers).map(key => {
          // 需要判断字段
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            // 格式化时间
            // 如果新添加的员工转正时间没有确定,需要再次判断
            if (item[headers[key]]) {
              return formatDate(item[headers[key]])
            } else {
              return '未知'
            }
          } else if (headers[key] === 'formOfEmployment') {
            // 通过枚举里面的数据对照 聘用形式
            // 如果可以找到对应id,就把所对应的value返回,否则返回未知
            const obj = EmployeeEnum.hireType.find(obj => obj.id === +item[headers[key]])
            return obj ? obj.value : '未知'
          }
          return item[headers[key]] // 张三, 13811111111, 2018, ...
        }) // => ["张三", "13811111111"，"2018","1", "2018", "10002"]
      }) // [["张三", "13811111111"，"2018","1", "2018", "10002"],["李四", "13911111111"，"2018","1", "2018", "10002"]]
      // 链式编程
      // return rows.map(item => Object.keys(headers).map(key => item[headers[key]]))
    }
  }
}
</script>

<style>

</style>
